import React, { Fragment, useEffect, useRef, useState } from 'react'
import { Menu, Layout, Avatar, Popover, Badge, List, Button, Dropdown, Switch } from 'antd'
import moment from 'moment'
import { BellOutlined, RightOutlined } from '@ant-design/icons'
import SelectLang from 'src/react-antd-i18n/SelectLang'
import { useIntl } from 'src/react-antd-i18n'
import styles from './index.module.less'
import classNames from 'classnames'

const Header = (props) => {

    const intl = useIntl();
    const [skin, setSkin] = useState('');
    const { theme, setTheme } = props;

    useEffect(() => {
        handleMenuItemClick({ key: skin })
    }, [theme])

    // 随机颜色
    function getRandomColor() {
        const rgb = []
        for (let i = 0; i < 3; ++i) {
            let color = Math.floor(Math.random() * 256).toString(16)
            color = color.length === 1 ? '0' + color : color
            rgb.push(color)
        }
        return '#' + rgb.join('')
    }

    //换肤（固定颜色）
    function handleMenuItemClick({ key }) {

        if (key === 'random1') {
            // 使用插件替换皮肤
            const color = getRandomColor()
            window.replaceStyleVariable && window.replaceStyleVariable({
                main: color,
                mainHover: color,
            })
            if (window.replaceStyleVariable) {
                console.log('替换完成')
            } else {
                console.log('不支持测试环境替换皮肤')
            }
            return
        } else if (key === 'random2') {
            // 测试环境使用less编辑切换皮肤
            const color = getRandomColor()
            console.log('开始编译：', color)
            if (window.less) {
                window.less.modifyVars({
                    '@primary-color': color,
                }).then(() => {
                    console.log('编译完成')
                })
            } else {
                window.less = {
                    async: true,
                    env: 'development',
                    javascriptEnabled: true
                }
                import('less').then(() => {
                    window.less.modifyVars({
                        '@primary-color': color,
                    }).then(() => {
                        console.log('编译完成')
                    })
                })
            }
            return
        } else {
            // 编译出的特定皮肤，使用标签替换
            let styleLink = document.getElementById('theme-style');
            const body = document.getElementsByTagName('body')[0];
            if (theme === 'dark' && !key.includes('dark')) {
                key = key ? `dark-${key}` : 'dark'
            } else if (theme !== 'dark' && key.includes('dark')) {
                key = key.split('-')[1]
            }
            if (!key) key = ''
            setSkin(key);
            body.className = `body-wrap-${key}`; // 切换自定义组件的主题
            if (styleLink) {
                // 假如存在id为theme-style 的link标签，直接修改其href
                styleLink.href = `/themes/${key}.css`; // 切换 antd 组件主题
            } else {
                // 不存在的话，则新建一个
                styleLink = document.createElement('link');
                styleLink.type = 'text/css';
                styleLink.rel = 'stylesheet';
                styleLink.id = 'theme-style';
                styleLink.href = `/themes/${key}.css`;
                document.body.append(styleLink);
            }

        }

    }

    //主题 白/黑
    function handleChangeTheme(checked) {
        let newTheme = checked ? 'dark' : 'light';
        setTheme(newTheme);
    }

    const menu = (<Menu
        theme={theme}
        onClick={handleMenuItemClick}
        items={[
            {
                key: 'random1',
                label: <div style={{ backgroundColor: '#fff' }}>随机替换</div>,

            },
            {
                key: 'random2',
                label: <div style={{ backgroundColor: '#fff' }}>随机编译</div>,

            },
            {
                key: '',
                label: <div style={{ backgroundColor: 'rgb(24, 144, 255)' }}>拂晓蓝</div>,
            },
            {
                key: 'dust',
                label: <div style={{ backgroundColor: 'rgb(245, 34, 45)' }}>薄暮</div>
            },
            {
                key: 'volcano',
                label: <div style={{ backgroundColor: 'rgb(250, 84, 28)' }}>火山</div>
            },
            {
                key: 'sunset',
                label: <div style={{ backgroundColor: 'rgb(250, 173, 20)' }}>日暮</div>
            },
            {
                key: 'cyan',
                label: <div style={{ backgroundColor: 'rgb(19, 194, 194)' }}>明青</div>
            },
            {
                key: 'green',
                label: <div style={{ backgroundColor: 'rgb(82, 196, 26)' }}>极光绿</div>
            },
            {
                key: 'geekblue',
                label: <div style={{ backgroundColor: 'rgb(47, 84, 235)' }}>极客蓝</div>
            },
            {
                key: 'purple',
                label: <div style={{ backgroundColor: 'rgb(114, 46, 209)' }}>酱紫</div>
            }
        ]}
    />)

    function handleMenuItemClick() {

    }

    return <Layout.Header
        className={classNames(styles.header, `ant-layout-header-${theme}`)}
        theme={theme}
    >
        <div className={styles.headerLeft}>
            <div className={styles.logo} />
            <Menu
                theme={theme}
                mode="horizontal"
                onClick={handleMenuItemClick}
                items={
                    [
                        {
                            key: '1',
                            label: '官网'
                        },
                        {
                            key: '2',
                            label: '简介'
                        },
                        {
                            key: '3',
                            label: '联系我们'
                        }
                    ]
                }
            />
        </div>
        <div className={styles.headerRight}>

            <Dropdown overlay={menu}>
                <Button>切换主题</Button>
            </Dropdown>

            <Switch
                checkedChildren="关灯"
                unCheckedChildren="开灯"
                onChange={handleChangeTheme} />

            <SelectLang />

            <Popover
                placement="bottomRight"
                trigger="click"
                key="notifications"
                overlayClassName="notificationPopover"
                getPopupContainer={trigger => trigger.parentElement}
                content={
                    <div>
                        <List
                            itemLayout="horizontal"
                            dataSource={props.notifications}
                            locale={{
                                emptyText: <span>You have viewed all notifications.</span>,
                            }}
                            renderItem={item => (
                                <List.Item className="notificationItem">
                                    <List.Item.Meta
                                        title={
                                            <span tooltip lines={1}>
                                                {item.title}
                                            </span>
                                        }
                                        description={moment(item.date).fromNow()}
                                    />
                                    <RightOutlined style={{ fontSize: 10, color: '#ccc' }} />
                                </List.Item>
                            )}
                        />
                        {props.notifications.length ? (
                            <div
                                onClick={props.onAllNotificationsRead}
                                className="clearButton"
                            >
                                <span>Clear notifications</span>
                            </div>
                        ) : null}
                    </div>
                }
            >
                <Badge
                    count={props.notifications.length}
                    dot={2}
                    offset={[-10, 10]}
                    className={styles.badgeNotification}
                >
                    <BellOutlined className={styles.iconNotification} />
                </Badge>
            </Popover>
            <Menu
                theme={theme}
                key="user"
                mode="horizontal"
                items={
                    [
                        {
                            key: '',
                            label: <div>
                                <span style={{ color: '#999', marginRight: 4 }}>
                                    Hi,
                                </span>
                                <span>xiaoming</span>
                                <Avatar style={{ marginLeft: 8 }} src={''} />
                            </div>,
                            children: [
                                {
                                    key: 'SignOut',
                                    label: '退出登录',
                                    a: <div>
                                        {intl.formatMessage({
                                            id: 'pages.login.success',
                                            defaultMessage: 'aaaaa',
                                        })}
                                    </div>
                                }
                            ]
                        }
                    ]
                }
            />
        </div>
    </Layout.Header>
}

export default Header